package com.gitee.wsl.struct.grammar.ast.process.constraints.ext

import com.gitee.wsl.text.reader.line.LookaheadText
import com.gitee.wsl.struct.grammar.ast.process.constraints.TextReadConstraints
import kotlin.math.min


fun TextReadConstraints.getCharsEaten(s: CharSequence): Int {
    return min(charsEaten, s.length)
}

fun TextReadConstraints.calcNumberOfConsequentEols(pos: LookaheadText.Position): Int {

    require(pos.offsetInCurrentLine == -1)

    var currentPos = pos
    var result = 1

    val isClearLine: (LookaheadText.Position) -> Boolean = { pos ->
        val currentConstraints = applyToNextLine(pos)
        val constraintsLength = currentConstraints.getCharsEaten(pos.currentLineText)

        currentConstraints.upstreamWith(this) && (
                constraintsLength >= pos.currentLineText.length ||
                        pos.nextPosition(1 + constraintsLength)?.charsToNonWhitespace() == null)
    }

    while (isClearLine(currentPos)) {
        currentPos = currentPos.nextLinePosition()
            ?: break//return 5

        result++
        if (result > 4) {
            break
        }
    }
    return result
}




